package com.zhenyi.tuangou.index;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.utils.AuthUtils;
import com.utils.interceptor.TestInterceptor;
import com.zhenyi.common.model.TgAddress;
import com.zhenyi.common.model.TgGroupProduct;
import com.zhenyi.common.model.TgProduct;
import com.zhenyi.common.model.TgUser;
import com.zhenyi.tuangou.interceptor.WXInterceptor;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;

public class HomeController extends TGController {

	private final String HOST = PropKit.get("host");

	@Clear
	@Before(TestInterceptor.class)
	public void debug() {
		TgUser user = TgUser.dao.findById(20180709);
		AuthUtils.login(String.valueOf(user.getId()), this);
		redirect("/tg");
	}

	@Clear
	@Before(TestInterceptor.class)
	public void debug1() {
		TgUser user = TgUser.dao.findById(20180708);
		AuthUtils.login(String.valueOf(user.getId()), this);
		redirect("/tg");
	}

	@Clear
	@Before(TestInterceptor.class)
	public void debug2() {
		TgUser user = TgUser.dao.findById(20180707);
		AuthUtils.login(String.valueOf(user.getId()), this);
		redirect("/tg");
	}

	/**
	 * 跳转去微信连接
	 */
	@Clear
	public void wx() {
		String rd = HOST + "/auth";
		rd = URLUtil.encode(rd);
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={}"
				+ "&redirect_uri={}&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";
		url = StrFormatter.format(url, APP_ID, rd);
		redirect(url);
	}

	/**
	 * 微信登录
	 */
	@Clear
	public void auth() {
		String code = getPara("code");
		if (StrKit.isBlank(code)) {
			renderError(404);
			return;
		}
		SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(APP_ID, APP_SECRET, code);
		String openId = snsAccessToken.getOpenid();
		String accessToken = snsAccessToken.getAccessToken();
		ApiResult snsApi = SnsApi.getUserInfo(accessToken, openId);
		/**
		 * 如果用户不存在,创建新用户
		 */
		TgUser user = TgUser.dao.searchFirst("openId", openId);
		if (user == null) {
			user = new TgUser();
			user.setOpenId(openId);
			user.save();
			user.setUid(hashids.encode(user.getId()));
		}
		user.setName(snsApi.getStr("nickname"));
		user.setLogo(snsApi.getStr("headimgurl"));
		user.update();
		AuthUtils.login(String.valueOf(user.getId()), this);
		String state = getPara("state");
		if (StrKit.isBlank(state)) {
			redirect("/tg");
		} else {
			redirect(URLUtil.decode(state));
		}
	}

	/**
	 * 需要用到微信功能页面要用这个拦截器
	 */
	@Clear()
	@Before(WXInterceptor.class)
	public void test() {
		// onMenuShareTimeline
		// onMenuShareAppMessage
		// onMenuShareQQ
		// onMenuShareWeibo
		// onMenuShareQZone
		// chooseWXPay
		renderSuccess();
		render("/res/test.html");
	}

	public void index() {
		Integer type = getParaToInt("type");// 默认全部类型
		Long shopId = getParaToLong("shopId", (long) 1802);// 商家id
		SqlPara sqlPara;
		if (type != null) {
			Kv cond = Kv.by("type", type);
			sqlPara = Db.getSqlPara("findProductByType", cond);
		} else {
			sqlPara = Db.getSqlPara("findProductByType");
		}
		// 商品列表
		List<Record> list = Db.find(sqlPara);
		Kv cond1 = Kv.by("shopId", shopId);
		SqlPara sqlPara2 = Db.getSqlPara("findProductType", cond1);
		List<Record> typeList = Db.find(sqlPara2);
		setAttr("typeList", typeList);
		setAttr("items", list);
		render("/res/index.html");
		redirect("/tg/community");

	}

	@Clear
	public void admin() {
		render("/admin/index.html");
	}

	public void productInfo() {
		render("/res/productInfo.html");
	}

	public void groupBuyingInfo() {
		render("/res/groupBuyingInfo.html");
	}

	public void groupBuyingResult() {
		render("/res/groupBuyingResult.html");
	}

	public void orderConfirm() {
		Integer productId = getParaToInt("id");// 商品ID
		if (productId == null) {
			renderFailure();
			renderError(500);
			return;
		}
		int userId = 20180701;
		TgUser user = TgUser.dao.findById(userId);// 获取当前用户

		TgAddress address = user.getDefaultAddress();// 用户默认地址
		TgProduct product = TgProduct.dao.findById(productId);// 购买商品信息
		setAttr("product", product);// 购买商品信息
		// setAttr("type", type);
		setAttr("address", address);// 默认地址

		Kv cond = Kv.by("userId", userId);
		SqlPara sql = Db.getSqlPara("findAddress", cond);
		List<Record> list = Db.find(sql);
		setAttr("addressList", list);

		TgGroupProduct groupProduct = TgGroupProduct.dao.findById(getParaToInt("groupId"));
		setAttr("price", groupProduct.getPrice());

		render("/res/orderConfirm.html");
	}

	public void orderInfo() {
		render("/res/orderInfo.html");
	}

	public void orderList() {
		Integer status = getParaToInt("status", 0);
		Long userId = 20180701L;
		Kv cond = Kv.by("userId", userId).set("status", status);
		SqlPara sql = Db.getSqlPara("findOrderByType", cond);
		List<Record> orderList = Db.find(sql);
		setAttr("orderList", orderList);
		render("/res/orderList.html");
	}

	/**
	 * 用户信息
	 */
	public void userHome() {
		TgUser user = getUser();
		setInfoItem(user);
		render("/res/userHome.html");
	}

	/**
	 * 打开分享连接
	 */
	public void shareGroup() {
		// String code = getPara(0);
		// Long groupId = hashids.decode(code)[0];
		// redirect("/group/findGroupProduct?groupBuyId=" + id);
	}

	public void signUp() {
		render("/res/signUp.html");
	}

	public void register() {
		String realName = getPara("name");
		String mobile = getPara("phone");
		Integer sex = getParaToInt("sex");
		Integer age = getParaToInt("age");
		String smsCode = getPara("code");

		TgUser user = getUser();
		if (!smsCode.equals(user.getSmsCode())) {
			renderFailure(401, "验证码不正确");
			return;
		}

		user.setRealName(realName);
		user.setMobile(mobile);
		user.setSex(sex);
		user.setAge(age);
		if (user.update()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void sms() {
		String mobile = getPara("phone");
		Long code = RandomUtil.randomLong(1000L, 9999L);
		String smsCode = code.toString();
		if (PropKit.getBoolean("devMode", false)) {
			smsCode = "1234";
		}
		TgUser user = getUser();
		user.setSmsCode(smsCode);
		user.update();
		renderSuccess();
	}

}
